'use strict'

const util = {
  noop: function () {},

  extend: function (dest, source) {
    for (let key in source) {
      if (source.hasOwnProperty(key)) {
        dest[key] = source[key];
      }
    }
    return dest;
  },

  objEqual: function (obj1, obj2) {
    for (let key in obj1) {
      if (obj1.hasOwnProperty(key)) {
        if (obj1[key] !== obj2[key]) {
          return false;
        }
      }
    }
    return true;
  },

  makeError: function (message, code) {
    const err = new Error(message);
    err.code = code;
    return err;
  },

  // 快速删除array中指定位置的元素,会破坏已有的排序
  quickUnorderArrayRemove: function (arr, i) {
    if (i >= arr.length || i < 0) return;
    const last = arr.pop();
    if (i < arr.length) {
      const tmp = arr[i];
      arr[i] = last;
      return tmp;
    }
    return last;
  },

  // 随机选取 0-high 之间的一个整数
  randomInt: function (high) {
    return Math.random() * high | 0;
  },

  randomIterate: function (list) {
    let offset = 0;

    return function () {
      if (offset == list.length) return null;

      const len = list.length - offset
        , i = util.randomInt(len)
        , el = list[offset + i]
        , tmp = list[offset];

      list[offset] = el;
      list[offset + i] = tmp;
      offset ++;

      return el;
    }
  },
}

module.exports = util;
